package com.docmanage.am.service.impl;

import com.docmanage.am.domain.AmApproval;
import com.docmanage.am.domain.AmBorrow;
import com.docmanage.am.domain.AmDescription;
import com.docmanage.am.domain.dto.AmApprovalDTO;
import com.docmanage.am.domain.dto.AmBorrowSearchDTO;
import com.docmanage.am.domain.dto.AmBorrowStatisticsDTO;
import com.docmanage.am.domain.dto.StatisticsBorrowDTO;
import com.docmanage.am.domain.vo.AmBorrowDetailsVo;
import com.docmanage.am.domain.vo.AmBorrowSearchVo;
import com.docmanage.am.domain.vo.AmBorrowStatisticsVO;
import com.docmanage.am.domain.vo.StatisticsBorrowVo;
import com.docmanage.am.mapper.AmBorrowMapper;
import com.docmanage.common.core.domain.entity.SysRole;
import com.docmanage.common.enums.BorrowStatus;
import com.docmanage.common.enums.StatusEnums;
import com.docmanage.common.utils.DateUtils;
import com.docmanage.common.utils.SecurityUtils;
import com.docmanage.common.utils.StringUtils;
import io.jsonwebtoken.lang.Objects;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.docmanage.common.utils.SecurityUtils.isAdmin;
import static com.docmanage.common.utils.SecurityUtils.isArchivesAdmin;

/**
 * 档案借阅Service业务层处理
 *
 * @author pointLion
 * @date 2023-06-18
 */
@Service
public class AmBorrowService {
    @Resource
    private AmBorrowMapper amBorrowMapper;

    @Resource
    private AmApprovalService amApprovalService;

    @Resource
    private AmDescriptionService descriptionService;

    /**
     * 查询档案借阅
     *
     * @param id 档案借阅主键
     * @return 档案借阅
     */
    public AmBorrowDetailsVo selectAmBorrowById(Long id) {
        AmBorrowDetailsVo amBorrowDetailsVo = new AmBorrowDetailsVo();
        AmBorrow amBorrow = amBorrowMapper.selectAmBorrowById(id);
        BeanUtils.copyProperties(amBorrow, amBorrowDetailsVo);
        if (!Objects.nullSafeEquals(amBorrowDetailsVo.getStatus(), StatusEnums.ZERO.getCode())) {
            //审批信息
            List<AmApproval> amApprovalList = amApprovalService.getAmApprovalByBorrowId(id);
            amBorrowDetailsVo.setAmApprovalList(amApprovalList);
        }
        StatusEnums statusEnums = StatusEnums.getNameByCode(amBorrow.getStatus());
        amBorrow.setStatusName(statusEnums.getName());
        return amBorrowDetailsVo;
    }


    public AmBorrowDetailsVo getApprovalInfo(Long id) {
        AmBorrowDetailsVo amBorrowDetailsVo = new AmBorrowDetailsVo();
        AmBorrow amBorrow = amBorrowMapper.selectAmBorrowById(id);
        BeanUtils.copyProperties(amBorrow, amBorrowDetailsVo);
        if (!Objects.nullSafeEquals(amBorrowDetailsVo.getStatus(), StatusEnums.ZERO.getCode())) {
            //审批信息
            List<AmApproval> amApprovalList = amApprovalService.getAmApprovalByBorrowId(id);
            if (amApprovalList.size() == 1) {
                amBorrowDetailsVo.setAmApproval(amApprovalList.get(0));
            } else {
                //获取审批中数据
                List<AmApproval> approvals = amApprovalList.stream().filter(item -> item.getState().equals(StatusEnums.ONE.getCode())).collect(Collectors.toList());
                amBorrowDetailsVo.setAmApproval(approvals.get(0));
                amApprovalList.removeAll(approvals);
            }
            amBorrowDetailsVo.setAmApprovalList(amApprovalList);
        }
        StatusEnums statusEnums = StatusEnums.getNameByCode(amBorrow.getStatus());
        amBorrow.setStatusName(statusEnums.getName());
        return amBorrowDetailsVo;
    }

    /**
     * 查询档案借阅列表
     *
     * @param searchDTO 档案借阅
     * @return 档案借阅
     */
    public List<AmBorrowSearchVo> selectAmBorrowList(AmBorrowSearchDTO searchDTO) {
        //如果不是admin用户，则只能查看自己创建的申请单
        if (isArchivesAdmin()) {
            //单据拥有者
            searchDTO.setNoStatus(StatusEnums.ZERO.getCode());
        }

        //amBorrow.setTenantId(SecurityUtils.getTenantId());
        List<AmBorrowSearchVo> amBorrowSearchVos = amBorrowMapper.selectAmBorrowList(searchDTO);
        amBorrowSearchVos.forEach(item -> {
            StatusEnums statusEnums = StatusEnums.getNameByCode(item.getStatus());
            item.setStatusName(statusEnums.getName());
        });
        return amBorrowSearchVos;
    }

    /**
     * 查询个人档案借阅列表
     *
     * @param searchDTO 档案借阅
     * @return 档案借阅
     */
    public List<AmBorrowSearchVo> selectPersonAmBorrowList(AmBorrowSearchDTO searchDTO) {
        searchDTO.setUserId(SecurityUtils.getUserId());
        List<AmBorrowSearchVo> amBorrowSearchVos = amBorrowMapper.selectAmBorrowList(searchDTO);
        amBorrowSearchVos.forEach(item -> {
            StatusEnums statusEnums = StatusEnums.getNameByCode(item.getStatus());
            item.setStatusName(statusEnums.getName());
        });
        return amBorrowSearchVos;
    }

    /**
     * 新增档案借阅
     *
     * @param amBorrow 档案借阅
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertAmBorrow(AmBorrow amBorrow) {
        amBorrow.setCreateTime(DateUtils.getNowDate());
        amBorrow.setCreateBy(SecurityUtils.getUsername());
        amBorrow.setDeptId(SecurityUtils.getDeptId());
        amBorrow.setUserId(SecurityUtils.getUserId());
        //通过预计借阅日期和归还日期计算借阅天数
        if (amBorrow.getDays() == null) {
            int i = DateUtils.differentDaysByMillisecond(amBorrow.getReckonBorrowTime(), amBorrow.getReckonReturnTime());
            amBorrow.setDays(new BigDecimal(i));
        }
        if (amBorrow.getStatus().equals(StatusEnums.ONE.getCode())) {
            //判断档案是否在库
            Boolean isExist = amBorrowMapper.selectAmBorrowListByDeptId(amBorrow.getDescId());
            if (!isExist) {
                return 0;
            }
        }
        int i = amBorrowMapper.insertAmBorrow(amBorrow);
        if (amBorrow.getStatus().equals(StatusEnums.ONE.getCode())) {
            submitBorrowForm(amBorrow.getId());
        }
        return i;
    }


    /**
     * 修改档案借阅
     *
     * @param amBorrow 档案借阅
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateAmBorrow(AmBorrow amBorrow) {
        amBorrow.setUpdateTime(DateUtils.getNowDate());
        amBorrow.setUpdateBy(SecurityUtils.getUsername());
        if (amBorrow.getStatus().equals(StatusEnums.ONE.getCode())) {
            //判断档案是否在库
            Boolean isExist = amBorrowMapper.selectAmBorrowListByDeptId(amBorrow.getDescId());
            if (!isExist) {
                return 0;
            }
        }
        int i = amBorrowMapper.updateAmBorrow(amBorrow);
        if (amBorrow.getStatus().equals(StatusEnums.ONE.getCode())) {
            submitBorrowForm(amBorrow.getId());
        }
        return i;
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateAmBorrowInfo(AmBorrow amBorrow) {
        amBorrow.setUpdateTime(DateUtils.getNowDate());
        amBorrow.setUpdateBy(SecurityUtils.getUsername());
        int i = amBorrowMapper.updateAmBorrow(amBorrow);
        return i;
    }

    /**
     * 批量删除档案借阅
     *
     * @param ids 需要删除的档案借阅主键
     * @return 结果
     */
    public int deleteAmBorrowByIds(Long[] ids) {
        return amBorrowMapper.deleteAmBorrowByIds(ids);
    }

    /**
     * 删除档案借阅信息
     *
     * @param id 档案借阅主键
     * @return 结果
     */
    public int deleteAmBorrowById(Long id) {
        return amBorrowMapper.deleteAmBorrowById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public int submitBorrowForm(Long id) {
        AmBorrow amBorrow = new AmBorrow();
        amBorrow.setId(id);
        amBorrow.setStatus(StatusEnums.ONE.getCode());
        amBorrow.setSubmitTime(new Date());
        int i = updateAmBorrowInfo(amBorrow);
        int j = 0;
        if (i == 1) {
            AmApproval amApproval = new AmApproval();
            amApproval.setApplicant(SecurityUtils.getUsername());
            amApproval.setApplicantId(SecurityUtils.getUserId());
            amApproval.setObjId(id);
            amApproval.setCreateBy(SecurityUtils.getUsername());
            amApproval.setUpdateBy(SecurityUtils.getUsername());
            j = amApprovalService.insertAmApproval(amApproval);
        }
        return j;
    }

    @Transactional(rollbackFor = Exception.class)
    public int approvalBorrowForm(AmApprovalDTO dto) {
        if (!isArchivesAdmin()) {
            return 2;
        }
        AmApproval amApproval = new AmApproval();
        BeanUtils.copyProperties(dto, amApproval);
        if (StringUtils.isBlank(dto.getRemark())) {
            amApproval.setRemark(dto.getApprovalOpinions());
        }
        amApproval.setApprovalId(SecurityUtils.getUserId());
        amApproval.setApprovalTime(new Date());
        int i = amApprovalService.updateAmApproval(amApproval);
        int j = 0;
        if (i == 1) {
            AmBorrow amBorrow = new AmBorrow();
            amBorrow.setStatus(amApproval.getState().toString());
            amBorrow.setId(amApproval.getObjId());
            j = amBorrowMapper.updateAmBorrow(amBorrow);
        }
        return j;
    }

    /**
     * 设置归还时间
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer setReturnTime(Long id) {
        AmBorrow amBorrow = new AmBorrow();
        amBorrow.setId(id);
        amBorrow.setReturnTime(new Date());
        amBorrow.setStatus(StatusEnums.FIVE.getCode());
        updateAmBorrowInfo(amBorrow);
        int i = updateAmBorrowInfo(amBorrow);
        if (i == 1) {
            return setBrStatus(id, BorrowStatus.ZERO.getCode());
        }
        return 0;
    }


    /**
     * 设置借阅时间
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer setBorrowTime(Long id) {
        AmDescription amDescription = descriptionService.selectAmDescriptionById(amBorrowMapper.selectAmBorrowById(id).getDescId(), null);
        if (amDescription.getBrStatus().equals(BorrowStatus.ONE.getCode())) {
            return 0;
        }
        AmBorrow amBorrow = new AmBorrow();
        amBorrow.setId(id);
        amBorrow.setBorrowTime(new Date());
        //不在库
        amBorrow.setStatus(StatusEnums.FOUR.getCode());
        int i = updateAmBorrowInfo(amBorrow);
        if (i == 1) {
            return setBrStatus(id, BorrowStatus.ONE.getCode());
        }
        return 0;
    }

    /**
     * 设置档案借阅状态
     *
     * @param id
     * @param status
     * @return
     */
    private Integer setBrStatus(Long id, String status) {
        Long descId = amBorrowMapper.selectAmBorrowById(id).getDescId();
        AmDescription amDescription = new AmDescription();
        amDescription.setId(descId);
        amDescription.setBrStatus(status);
        return descriptionService.updateAmDescription(amDescription);
    }


    /**
     * 借阅统计
     *
     * @param dto 档案借阅
     * @return 结果
     */
    public List<StatisticsBorrowVo> statisticsBorrow(StatisticsBorrowDTO dto) {
        List<StatisticsBorrowVo> list = amBorrowMapper.statisticsBorrow(dto);
        return list;
    }


    /**
     * 档案借阅撤销
     *
     * @param id 借阅id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int repeal(Long id) {
        AmBorrow amBorrow = new AmBorrow();
        amBorrow.setId(id);
        amBorrow.setStatus("0");
        int i = amBorrowMapper.updateAmBorrow(amBorrow);
        if (i == 1) {
            int j = amApprovalService.deleteApprovalByObjId(id);
            return j;
        }
        return 0;
    }

    public List<AmBorrowStatisticsVO> borrowStatistics(AmBorrowStatisticsDTO dto) {
        /**
         * 未借出过的不展示
         */
        List<AmBorrowStatisticsVO> list = amBorrowMapper.borrowStatistics(dto).stream().filter(item -> (item.getLendNum() != 0 || item.getBorrowNum() != 0)).collect(Collectors.toList());
        return list;
    }
}
